import type { BaseProfile, LoginResult } from '@/types/user';
import { defineStore } from 'pinia';
import $apiUser from '@/api/user';
import { useAppStore } from '@/stores/modules/app';

interface User {
    userInfo: BaseProfile;
    token: string;
}
// 定义 Store
export const useUserStore = defineStore('user', {
    state: (): User => ({
        userInfo: {
            userId: undefined,
            userIndexId: undefined,
            avatar: undefined,
            nickname: undefined,
            mobile: undefined,
        },
        token: '',
    }),
    getters: {
        login(): boolean {
            return !!this.token;
        },
    },
    actions: {
        loginSuccess(data: any) {
            this.userInfo.userId = data.userId;
            this.userInfo.userIndexId = data.userIndexId;
            this.token = data.token;
            $apiUser.getInfo().then(({ data }) => {
                this.setUserInfo(data);
            });

            if (useAppStore().pageAfterLogin) {
                uni.redirectTo({
                    url: useAppStore().pageAfterLogin,
                    complete(e) {
                        useAppStore().setPageAfterLogin('');
                    },
                });
                return;
            }
            uni.reLaunch({
                url: '/pages/index/index',
            });
        },
        setUserInfo(data: LoginResult) {
            this.token = data.token;
            this.userInfo = data;
        },
        clearUserInfo() {},
    },
    // 网页端配置
    // persist: true,
    // 小程序端配置
    persist: {
        storage: {
            getItem(key) {
                return uni.getStorageSync(key);
            },
            setItem(key, value) {
                uni.setStorageSync(key, value);
            },
        },
    },
});
